package com.smartfast4j.backend.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.smartfast4j.backend.common.bean.R;
import com.smartfast4j.backend.common.util.ShiroUtils;
import com.smartfast4j.backend.modules.sys.entity.SysUser;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.MessageFormat;

/**
 * 登录拦截器
 * @author 孤傲苍狼
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    //log4j日志打印器
    private static final Logger logger = Logger.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.debug("----进入LoginInterceptor拦截器的preHandle方法---");
        SysUser loginSysUser = ShiroUtils.getLoginSysUser();//获取当前登录的系统用户
        logger.debug("获取到的登录用户信息，loginSysUser="+ JSON.toJSONString(loginSysUser));
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String uri = request.getRequestURI();
        logger.debug("----请求的uri地址：" + uri);
        //判断session里是否有用户信息
        if (loginSysUser == null) {
            logger.debug("登录已经失效，需要重新登录");
            if (request.getHeader("x-requested-with") != null
                    && request.getHeader("x-requested-with")
                    .equalsIgnoreCase("XMLHttpRequest"))//如果是ajax请求响应头会有，x-requested-with；
            {
                logger.debug("----本次请求为AJAX请求-----");
                response.setHeader("sessionStatus", "timeout");//在响应头设置session状态
            }else{
                logger.debug("----本次请求为普通请求-----");
                R r = R.error(1,"登录已经失效，需要重新登录");
                write(JSONObject.toJSONString(r), response);
            }
            return false;
        }
        logger.debug("用户处于正常登录状态，正常处理请求");
        return true;
    }

    /**
     * 写出数据
     *
     * @param res 输出的字符串
     * @throws Exception
     */
    protected void write(String res, HttpServletResponse response) {
        Writer writer = null;
        try {
            res = (null == res ? "" : res);
            response.setCharacterEncoding("UTF-8");
            //response.setHeader("Content-type", "text/html;charset=UTF-8");
            response.setHeader("Content-type", "application/json;charset=UTF-8");
            writer = response.getWriter();
            logger.debug("输出JSON字符串：" + res);
            writer.write(res);
        } catch (IOException e) {
            logger.error("输出JSON字符串异常", e);
        } finally {
            IOUtils.closeQuietly(writer);
        }
    }
}
